<template>
  <div class="feedback-page">
    <el-card class="feedback-card">
      <template #header>
        <div class="card-header">
          <h2>意见反馈</h2>
          <p class="subtitle">帮助我们做得更好</p>
        </div>
      </template>

      <el-form 
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="反馈类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择反馈类型">
            <el-option label="功能建议" value="feature" />
            <el-option label="问题反馈" value="bug" />
            <el-option label="使用咨询" value="usage" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>

        <el-form-item label="反馈内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="6"
            placeholder="请详细描述您的反馈内容..."
          />
        </el-form-item>

        <el-form-item label="图片">
          <el-upload
            class="feedback-uploader"
            :action="`${API_BASE_URL}/api/feedback/upload`"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            multiple
            :limit="3"
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              上传截图
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 jpg/png 文件，每个不超过 2MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="submitFeedback"
            :loading="submitting"
          >
            提交反馈
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 历史反馈列表 -->
      <el-divider>历史反馈</el-divider>

      <el-table
        v-loading="loading"
        :data="feedbackList"
        style="width: 100%"
      >
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTag(scope.row.type)">
              {{ getTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="content" label="内容" show-overflow-tooltip />
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="created_at" label="提交时间" width="180" />
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import axios from 'axios'

const API_BASE_URL = 'http://localhost:5000'
const formRef = ref(null)
const submitting = ref(false)
const loading = ref(false)

// 表单数据
const formData = reactive({
  type: '',
  content: '',
  images: []
})

// 表单验证规则
const rules = {
  type: [
    { required: true, message: '请选择反馈类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入反馈内容', trigger: 'blur' },
    { min: 10, message: '内容不能少于10个字符', trigger: 'blur' }
  ]
}

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const feedbackList = ref([])

// 上传相关
const uploadHeaders = {
  'Authorization': `Bearer ${localStorage.getItem('token')}`
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleUploadSuccess = (response) => {
  if (response.status === 'success') {
    formData.images.push(response.data.url)
    ElMessage.success('上传成功')
  }
}

const handleUploadError = () => {
  ElMessage.error('上传失败')
}

// 提交反馈
const submitFeedback = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const token = localStorage.getItem('token')
        const response = await axios.post(
          `${API_BASE_URL}/api/feedback`,
          formData,
          {
            headers: {
              'Authorization': `Bearer ${token}`
            }
          }
        )
        
        if (response.data.status === 'success') {
          ElMessage.success('提交成功')
          // 重置表单
          formRef.value.resetFields()
          formData.images = []
          // 刷新列表
          fetchFeedbackList()
        }
      } catch (error) {
        ElMessage.error('提交失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 获取反馈列表
const fetchFeedbackList = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get(
      `${API_BASE_URL}/api/feedback`,
      {
        params: {
          page: currentPage.value,
          per_page: pageSize.value
        },
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }
    )
    
    if (response.data.status === 'success') {
      feedbackList.value = response.data.data.records
      total.value = response.data.data.total
    }
  } catch (error) {
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchFeedbackList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchFeedbackList()
}

// 类型和状态标签
const getTypeLabel = (type) => {
  const types = {
    feature: '功能建议',
    bug: '问题反馈',
    usage: '使用咨询',
    other: '其他'
  }
  return types[type] || type
}

const getTypeTag = (type) => {
  const tags = {
    feature: 'success',
    bug: 'danger',
    usage: 'warning',
    other: 'info'
  }
  return tags[type] || ''
}

const getStatusLabel = (status) => {
  const statuses = {
    pending: '待处理',
    processing: '处理中',
    resolved: '已解决',
    closed: '已关闭'
  }
  return statuses[status] || status
}

const getStatusTag = (status) => {
  const tags = {
    pending: 'info',
    processing: 'warning',
    resolved: 'success',
    closed: ''
  }
  return tags[status] || ''
}

onMounted(() => {
  fetchFeedbackList()
})
</script>

<style scoped>
.feedback-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.feedback-card {
  margin-bottom: 20px;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.subtitle {
  margin: 10px 0 0;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.feedback-uploader {
  margin-top: 8px;
}

.el-upload__tip {
  margin-top: 8px;
  color: var(--el-text-color-secondary);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 